const Promise = require('../plugins/es6-promise.js').Promise

function promisify() {
  wx.pro = {} //wx.pro 下面挂载着返回的 promise 的wx.API

  wx.pro.getStorate = (key) => {
    return new Promise((resolve, reject) => {
      wx.getStorage({
        key: key,
        success: function(res) {
          resolve(res.data)
        },
        fail: err => {
          resolve(err)
        }
      })
    })
  }

  wx.pro.setStorage = (key, value) => {
    return new Promise((resolve, reject) => {
      wx.setStorage({
        key: key,
        data: value,
        success: res => {
          resolve(value)
        },
        fail: err => {
          resolve(err)
        }
      })
    })
  }

  wx.pro.request = options => {
    //toast
    if (options.toast) {
      wx.showToast({
        title: '加载中',
        icon: 'loading'
      })
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: options.url,
        method: options.method || 'GET',
        data: options.data,
        header: options.header || {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        success: res => {
          if (res.statusCode >= 400) {
            console.error('wx.request failed [business]', res.statusCode, res.data)
            reject(res)
          } else {
            console.log('wx.request success', res.data)
            resolve(res)
          }
        },
        fail: err => {
          console.error('wx.request failed [network]', err)
          reject(err)
        }
      })
    })
  }
}

promisify()

module.exports = Promise